<template>
  <div class="custom-widget-mnt">
    <div class="center-left">
      <div class="topBtn">
        <div class="left">
          <p>应用列表</p>
        </div>
        <div class="right">
          <button title="添加" type="button" class="ant-btn ant-btn-link ant-btn-icon-only" @click="addApp">
            <a-icon type="plus"/>
          </button>
          <button title="上移" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
            <a-icon type="arrow-up"/>
          </button>
          <button title="下移" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
            <a-icon type="arrow-down"/>
          </button>
          <button title="导出" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
            <a-icon type="export"/>
          </button>
          <span>
            <div class="ant-upload ant-upload-select ant-upload-select-text">
              <span role="button" tabindex="0" class="ant-upload">
                <input type="file" accept=".bml" style="display: none;">
                <button title="导入" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
                  <a-icon type="import"/>
                </button>
              </span>
            </div>
            <div class="ant-upload-list ant-upload-list-text"></div>
          </span>
        </div>
      </div>
      <div style="overflow-y: auto; height: calc(100% - 40px);">
        <a-table
          class="dist-simple-table w-full"
          rowKey="id"
          :columns="table1.columns"
          :customRow="table1.customRow"
          :data-source="table1.dataList"
          :row-selection="table1.rowSelection"
          :pagination="false"
        >
          <template slot="operate" slot-scope="text,record">
            <div class="display-flex">
              <a-icon type="edit" width="16px" height="16px" theme="outlined" @click="onEdit(record)"/>
              &nbsp;
              <a-icon type="delete" @click="onDelete(record)"/>
            </div>
          </template>
        </a-table>
      </div>
    </div>
    <div style="width: 70%; border-left: 1px solid rgb(232, 232, 232);">
      <div class="custom-widget-detail-mnt" style="display: flex; height: 100%;">
        <div style="width: 55%; border-right: 1px solid rgb(232, 232, 232);">
          <div class="topBtn">
            <div class="left">
              <p>模块 - </p>
            </div>
            <div class="right">
              <button title="添加" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
                <a-icon type="plus" />
              </button>
              <button title="上移" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
                <a-icon type="arrow-up" />
              </button>
              <button title="下移" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
                <a-icon type="arrow-down" />
              </button>
            </div>
          </div>
          <div style="overflow-y: auto; height: calc(100% - 40px);">
            <a-table
              class="dist-simple-table w-full"
              rowKey="id"
              :columns="table2.columns"
              :customRow="table2.customRow"
              :data-source="table2.dataList"
              :row-selection="table2.rowSelection"
              :pagination="false"
            >
              <template slot="operate" slot-scope="text,record">
                <div class="display-flex">
                  <a-icon type="edit" width="16px" height="16px" theme="outlined" @click="onEdit(record)"/>
                  &nbsp;
                  <a-icon type="delete" @click="onDelete(record)"/>
                </div>
              </template>
            </a-table>
          </div>
        </div>
        <div style="width: 45%; margin-left: 5px; border-left: 1px solid rgb(232, 232, 232);">
          <div class="custom-widget-btn-ctl" style="height: 100%;">
            <div class="topBtn">
              <div class="left">
                <p>按钮 - </p>
              </div>
              <div class="right">
                <button title="添加" type="button" class="ant-btn ant-btn-link ant-btn-icon-only">
                  <a-icon type="plus" />
                </button>
              </div>
            </div>
            <div style="overflow-y: auto; height: calc(100% - 150px);">
              <a-table
                class="dist-simple-table w-full"
                rowKey="id"
                :columns="table3.columns"
                :data-source="table3.dataList"
                :row-selection="table3.rowSelection"
                :pagination="false"
              >
                <template slot="operate" slot-scope="text,record">
                  <div class="display-flex">
                    <a-icon type="edit" width="16px" height="16px" theme="outlined" @click="onEdit(record)"/>
                    &nbsp;
                    <a-icon type="delete" @click="onDelete(record)"/>
                  </div>
                </template>
              </a-table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import invService from '@/api/invService'
import appService from '@/api/system/appService'
import versionService from '@/api/system/versionService'

const columns1 = [
  {
    title: 'name',
    dataIndex: 'name',
    align: 'center'
  },
  {
    title: 'operate',
    dataIndex: 'operate',
    width: '100px',
    align: 'center',
    scopedSlots: { customRender: 'operate' }
  }
]

export default {
  name: 'AppManage',
  data () {
    return {
      table1: {
        columns: columns1,
        customRow: (record, rowIndex) => {
          return {
            style: {
              'background-color': record.expanded ? '#f8f9fb !important' : '#ffffff !important',
              'font-weight': record.expanded ? 'bold' : 'normal'
            },
            on: {
              click: () => {},
              dblclick: () => { this.getModulesDataList(record) }
            }
          }
        },
        dataList: [],
        rowSelection: {
          selectedRowKeys: [],
          selectedRow: {},
          onChange: (selectedRowKeys, selectedRows) => {
            console.log(1)
            this.table1.rowSelection.selectedRowKeys = selectedRowKeys.length ? [selectedRowKeys.pop()] : []
            this.table1.rowSelection.selectedRow = selectedRows.length ? selectedRows.pop() : {}
          }
        }
      },
      table2: {
        columns: columns1,
        customRow: (record, rowIndex) => {
          return {
            style: {
              'background-color': record.expanded ? '#f8f9fb !important' : '#ffffff !important',
              'font-weight': record.expanded ? 'bold' : 'normal'
            },
            on: {
              click: () => {},
              dblclick: () => { this.getButtonDataList(record) }
            }
          }
        },
        dataList: [],
        rowSelection: {
          selectedRowKeys: [],
          selectedRow: {},
          onChange: (selectedRowKeys, selectedRows) => {
            this.table1.rowSelection.selectedRowKeys = selectedRowKeys.length ? [selectedRowKeys.pop()] : []
            this.table1.rowSelection.selectedRow = selectedRows.length ? selectedRows.pop() : {}
          }
        }
      },
      table3: {
        columns: columns1,
        dataList: [],
        rowSelection: {
          selectedRowKeys: [],
          selectedRow: {},
          onChange: (selectedRowKeys, selectedRows) => {
            this.table1.rowSelection.selectedRowKeys = selectedRowKeys.length ? [selectedRowKeys.pop()] : []
            this.table1.rowSelection.selectedRow = selectedRows.length ? selectedRows.pop() : {}
          }
        }
      },
      invItemList: [],
      invItemSelected: null,
      invItemCategory: 'common',
      invItemFormList: [],
      sourceInvItemFormList: [],
      expandedKeys: [],
      isShowEncrypt: false,
      checkedKeys: []
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    async getAppDataList () {
      const res = await appService.listCustomWidgetByParentId('/')
      const d = res.map(item => ({
        id: item.id,
        parentId: item.parentId,
        name: item.name
      }))
      if (d && d.length > 0) {
        this.table1.dataList = d
      }
    },
    async getModulesDataList (appData) {
      if (!appData || !appData.id) {
        return
      }
      appService.listCustomWidgetWithOutBtnByParentId(appData.id).then(res => {
        this.table2.dataList = res.map(item => ({
          id: item.id,
          parentId: item.parentId,
          name: item.name
        }))
      })
    },
    getButtonDataList () {
      console.log('getButtonDataList')
    },
    addApp (record) {
      const that = this
      this.$dialog({
        title: record ? '添加应用' : '修改版本',
        content: () => import('./AppDialog.vue'),
        width: window.document.body.clientWidth * 0.3 + 'px',
        bodyStyle: { height: window.document.body.clientWidth * 0.2 + 'px', padding: '0' },
        centered: true,
        maskClosable: false,
        okButtonProps: {},
        props: {
          record: record
        },
        model: {},
        on: {
          async ok (ctl) {
            const dialogCtl = ctl.getDialogCtl()
            const versionData = dialogCtl.getDataInfoResult()
            console.log('versionData', versionData)
            if (!versionData.versionNum) {
              that.$message.warning('请输入有效版本号')
              return
            }
            if (!versionData.publishDate) {
              that.$message.warning('请输入发布日期')
              return
            }
            if (!versionData.content) {
              that.$message.warning('请输入版本内容')
            }
            await versionService.save(versionData)
            that.$message.success('保存成功')
            await that.loadData()
            ctl.closeDialog()
          }
        }
      })
    },
    async init () {
      await this.getAppDataList()
      if (this.table1.dataList.length > 0) {
        console.log(2)
        await this.getModulesDataList(this.table1.dataList[0])
      }
      // this.getAllInvItemList()
    },
    handlerCheck (checkedKeys, e) {
      const record = e.node.$vnode.data.props.dataRef
      record.encrypt = e.checked
    },
    async handlerSaveData () {
      const data = this.sourceInvItemFormList
      const needData = []
      data.forEach(item => {
        needData.push({
          id: item.id,
          encrypt: item.encrypt
        })
      })
      await invService.updateItemFormEncrypt(needData)
      this.$message.success('保存成功')
    },
    handlerShowEncryptChange () {
      this.mergeInvestmentFormList()
    },
    handlerInvItemCategoryChange () {
      this.getInvestmentItemFormList()
    },
    handlerInvItemSelected (record) {
      if (record !== this.invItemSelected) {
        this.invItemSelected = record
        this.getInvestmentItemFormList()
      }
    },
    treeDataByParentCode (data, targetList, parentMap) {
      data.forEach(item => {
        if (item.parent_code) {
          const parent = parentMap[item.parent_code]
          if (parent) {
            parent.children.push(item)
          }
        }
      })
    },
    mergeInvestmentFormList () {
      const data = this.sourceInvItemFormList
      this.invItemFormList = []
      this.expandedKeys = []
      this.checkedKeys = []
      const targetList = []
      const parentMap = {}
      data.forEach(item => {
        if (!item.parent_code) {
          targetList.push(item)
        }
        item.children = []
        if (item.name) {
          item.title = `${item.code}(${item.name})`
        } else {
          item.title = item.code
        }
        parentMap[item.code] = item
      })
      this.treeDataByParentCode(data, targetList, parentMap)

      if (this.isShowEncrypt) {
        this.sourceInvItemFormList.forEach(item => {
          const parentCode = item.parent_code
          if (parentCode && parentMap[parentCode]) {
            item.parent = parentMap[parentCode]
          }
        })
        this.sourceInvItemFormList.forEach(item => {
          if (item.encrypt) {
            let parent = item.parent
            if (!item.children || item.children.length <= 0) {
              this.checkedKeys.push(item.id)
            }
            while (parent) {
              parent.encrypt = true
              parent = parent.parent
            }
          }
        })
        const newTargetList = []
        targetList.forEach(item => {
          if (item.encrypt) {
            newTargetList.push(item)
          }
        })
        const expendKeys = []
        Object.keys(parentMap).forEach(key => {
          if (parentMap[key].children.length > 0) {
            expendKeys.push(parentMap[key].id)
          }
        })
        this.invItemFormList = newTargetList
        this.expandedKeys = expendKeys
      } else {
        const expendKeys = []
        this.sourceInvItemFormList.forEach(item => {
          if (item.encrypt) {
            if (!item.children || item.children.length <= 0) {
              this.checkedKeys.push(item.id)
            }
          }
        })
        Object.keys(parentMap).forEach(key => {
          if (parentMap[key].children.length > 0) {
            expendKeys.push(parentMap[key].id)
          }
        })
        this.invItemFormList = targetList
        this.expandedKeys = expendKeys
      }
      console.log('checkedKeys', this.checkedKeys)
    },
    async getInvestmentItemFormList () {
      let data = null
      if (this.invItemSelected.item_code) {
        data = await invService.getInvestmentItemFormList(this.invItemSelected.item_code, this.invItemCategory, this.invItemSelected.source)
      } else {
        data = await invService.listInvestmentItemSystemForm({
          category: this.invItemCategory,
          source: this.invItemSelected.source
        })
      }
      this.sourceInvItemFormList = data
      this.mergeInvestmentFormList()
    },
    async getAllInvItemList () {
      const data = await invService.getAllInvestmentItemList({})

      this.invItemList = data
      data.unshift({
        id: -2,
        approve_type: '01',
        item_code: '',
        item_name: '3.0大项目基础信息',
        source: 'investment_three_old'
      })
      data.unshift({
        id: -1,
        approve_type: '01',
        item_code: '',
        item_name: '3.0大项目基础信息',
        source: 'investment_three_new'
      })

      this.handlerInvItemSelected(this.invItemList[0])
    }
  }
}
</script>

<style scoped lang="less">
.custom-widget-mnt {
  display: flex;
  flex-direction: row;
  padding: 10px;
  height: 100%;
  background-color: #fff;
  margin: 0;

  .center-left {
    width: 30%;
    margin-right: 5px;
    border-right: 1px solid #e8e8e8;
    border-left: 1px solid #e8e8e8;
    height: 100%;
  }

  .topBtn {
    background: #eceded;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;

    .left {
      float: left;
      margin-left: 5px;

      p {
        margin: 11px 0;
      }
    }

    .right {
      float: right;
    }

    .ant-btn {
      margin: 5px 0 5px 5px;
      padding: 0 5px;
    }
  }
}

.custom-widget-detail-mnt {

}

.item-form-encrypt-mnt {
  background-color: white;
  padding: 10px;

  .content-box {
    .info-box {
      border: 2px solid #ebedf1;

      .title-box {
        height: 40px;
        font-weight: bolder;
        font-size: 18px;
        background-color: #ebedf1;
      }

      .list-box {
        .list-item {
          flex-shrink: 0;
          justify-content: flex-start;
          padding: 10px 10px;
          margin-top: 10px;

          &:hover {
            cursor: pointer;
            background-color: rgba(235, 237, 241, 0.7);
          }

          &-selected {
            background-color: #f2fcff;
            color: #2BAEF2;
            font-weight: bolder;
          }
        }

      }

    }
  }

  .bg-border {
  }
}
</style>
